import { ref, onMounted, onUnmounted } from 'vue'
import { useGameStore } from '@/store/gameStore'
import { useResourcesStore } from '@/store/resources'
import { useLogStore } from '@/store/log'
import dayjs from 'dayjs'

/**
 * 游戏循环组合式函数
 * 处理游戏的主循环逻辑，包括资源更新、状态检查等
 */
export function useGameLoop() {
  // 获取store
  const logStore = useLogStore()
  const gameStore = useGameStore()
  const resourcesStore = useResourcesStore()

  // 游戏循环ID
  const loopId = ref<number | null>(null)

  // 游戏更新间隔（毫秒）
  const updateInterval = 1000 // 每秒更新一次

  // 时间累积器
  let timeAccumulator = 0

  /**
   * 启动游戏循环
   */
  const startGameLoop = () => {
    if (loopId.value) return

    gameStore.startGame()

    let lastTime = performance.now()

    const gameLoop = () => {
      const currentTime = performance.now()
      const deltaTime = currentTime - lastTime

      timeAccumulator += deltaTime

      if (timeAccumulator > updateInterval) {
        gameStore.update()
        timeAccumulator -= updateInterval
      }

      lastTime = currentTime
      loopId.value = requestAnimationFrame(gameLoop)
    }

    loopId.value = requestAnimationFrame(gameLoop)
  }

  /**
   * 停止游戏循环
   */
  const stopGameLoop = () => {
    if (loopId.value) {
      cancelAnimationFrame(loopId.value)
      loopId.value = null
      gameStore.pauseGame()
      logStore.addLog({
        type: 'warning',
        source: 'system',
        content: '游戏已暂停',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
    }
  }

  const resumeGameLoop = () => {
    if (loopId.value) {
      let lastTime = performance.now()

      const gameLoop = () => {
        const currentTime = performance.now()
        const deltaTime = currentTime - lastTime

        timeAccumulator += deltaTime

        if (timeAccumulator > updateInterval) {
          gameStore.update()
          timeAccumulator -= updateInterval
        }

        lastTime = currentTime
        loopId.value = requestAnimationFrame(gameLoop)
      }

      loopId.value = requestAnimationFrame(gameLoop)
    }
  }

  /**
   * 切换游戏运行状态
   */
  const toggleGameLoop = () => {
    if (gameStore.gameState.isRunning) {
      stopGameLoop()
    } else {
      logStore.addLog({
        type: 'warning',
        source: 'system',
        content: '游戏已恢复',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
      startGameLoop()
    }
  }

  // 组件卸载时自动停止游戏循环
  onUnmounted(() => {
    stopGameLoop()
  })

  return {
    startGameLoop,
    stopGameLoop,
    toggleGameLoop,
    resumeGameLoop,
    isRunning: () => gameStore.gameState.isRunning,
  }
}
